Categories
Modern JavaScript

Best Features of ES2018 — Promise finally and Template Restrictions

Spread the love

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at the best features of ES2018.

Promise.prototype.finally()

The finally method is added to the Promise instance to run some code regardless of the outcome of the promise.

For instance, we can write:

promise
  .then(result => {
    //...
  })
  .catch(error => {
    //...
  })
  .finally(() => {
    //...
  });

The then callback is run when promise is fulfilled.

catch callback is run when promise is rejected.

finally callback is run regardless of the outcome.

So:

promise
  .finally(() => {
    //...
  });

is the same as:

promise
  .then(
    result => {
      //...
      return result;
    },
    error => {
      //...
      throw error;
    }
  );

The most common use case is similar to the synchronous finally clause.

It lets us clean up after we’re done with a resource.

finally() is the same as finally {} is synchronous code.

The try clause corresponds to the promise’s then callback.

catch is like .catch in promises.

finally is like .finally in promises.

Template Literal Changes

Tag functions how work wirh escape sequences.

For instance, we can write:

const raw = String.raw\`\u{50}`

Then we get '\u{50}' in raw form.

So we get:

function tag(str) {
  console.log(str);
}

tag `\u{50}`

as the value of str :

["P", raw: Array(1)]

The cooked form is 'P' and the raw version is what we had.

Not all text is illegal with backslashes.

So writing something like:

`unicode`

won’t work.

ES2018 drops the syntactic restrictions so that we can enter these kinds of character combinations into the template literal.

Conclusion

Template literal syntax is now less restrictive than before with ES2018.

Some escape sequences are looser.

Also, the finally method is added to Promise instances so that we can run code regardless of the outcome of the promise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *